package com.zhifou.handler;

import com.zhifou.constants.RedisPrefix;
import com.zhifou.model.User;
import com.zhifou.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 知否技术
 * @description 请求拦截器
 * @date 2023-02-23 9:51
 */
@Component
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开启拦截器----->");
        // 不是方法，直接放开
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null) {
            throw new Exception("token已失效，请重新登录");
        }
        if (!jwtUtil.verifyToken(token) || jwtUtil.isExpire(token)) {
            throw new Exception("token已失效，请重新登录");
        }
        // 用户信息
        User user = (User) redisTemplate.opsForValue().get(RedisPrefix.TOKEN_USER_LOGIN + token);
        if (null == user) {
            throw new Exception("用户不存在");
        }
        request.setAttribute("currentUser", user);
        return true;
    }
}
